import 'package:flutter/material.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/model/subject/rank_error_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';
import 'package:hktk_app/widget/subject/sift_item_widget.dart';

/// 热点试题页面
class DoingSiftPage extends StatefulWidget {
  const DoingSiftPage({super.key});

  @override
  State<DoingSiftPage> createState() => _DoingSiftPageState();
}

class _DoingSiftPageState extends State<DoingSiftPage> {
  late BuildContext _context;

  /// 初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<RankErrorModel> _list;

  @override
  void initState() {
    super.initState();
    debugPrint("doingSiftPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("doingSiftPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: SafeArea(child: Column(
        children: [
          PageTitleWidget(
            name: "热点试题",
            pageContext: context,
          ),
          Expanded(child: _futureData()),
        ],
      )),
    );
  }

  /// 异步加载方法
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
        BuildContext context,
        AsyncSnapshot<Map<String, dynamic>> snapshot,
      ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      _list = await SubjectDao.categoryRank(
        examId: dataUtilComm.dataModel.examId,
        categoryId: dataUtilComm.dataModel.categoryId,
      );

      map["suc"] = true;
    } catch (e) {
      debugPrint("doingSiftPage 页面 -> 热点试题页面加载数据方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("doingSiftPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示组件
  _content() {
    if (_list.isNotEmpty) {
      return Padding(
        padding: EdgeInsets.all(30),
        child: MediaQuery.removePadding(
          removeTop: true,
          context: _context,
          child: ListView.separated(
            itemBuilder: _itemBuilder,
            separatorBuilder: _separatorBuilder,
            itemCount: _list.length + 1,
          ),
        ),
      );
    } else {
      return Center(
        child: Text(
          "暂无数据",
          style: FontUtil.fontGrey1(30),
        ),
      );
    }
  }

  /// 内容显示组件
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      RankErrorModel rank = _list[index];
      return SiftItemWidget(
        index: index + 1,
        rank: rank,
        count: rank.doCount ?? 0,
        rType: CtEnum.hotQue,
      );
    } else {
      return _tipsItem();
    }
  }

  /// 间隔显示组件
  Widget _separatorBuilder(BuildContext context, int index) {
    return hiSpace(height: 20);
  }

  /// 底部到底提示组件
  Widget _tipsItem() {
    return Container();
    // return SizedBox(
    //   height: 80,
    //   child: Center(
    //     child: Text(
    //       "我是有底线的！",
    //       style: FontUtil.fontBlue1(28),
    //     ),
    //   ),
    // );
  }
}
